import React, { useState } from 'react';
import { Tabs, Select, DatePicker, Button, Card, Row, Col, List, Space } from 'antd';

const { TabPane } = Tabs;
const { RangePicker } = DatePicker;

// 模拟的项目消息数据
const mockMessages = [
  {
    id: 1,
    title: '项目回款提醒',
    status: '已读',
    type: 'payment',
    timestamp: '2025-06-17 17:45',
    details: {
      '合同编号': 'FHCZ01830046-20220509-C01',
      '合同名称': '丰库CRM系统开发合同',
      '回款单编号': 'FHCZ01830046-20220509-C01',
      '应收阶段': '产品阶段确认',
      '回款金额': '¥1,000.00',
    },
  },
  {
    id: 2,
    title: '任务指派提醒',
    status: '已读',
    type: 'task',
    timestamp: '2025-06-18 17:45',
    details: {
      '所属项目': '产品事业部CRM系统',
      '任务名称': '产品阶段',
      '任务工期': '30天',
      '任务周期': '2022.05.10 - 2022.07.10',
    },
  },
  {
    id: 3,
    title: '项目进度提醒',
    status: '已读',
    type: 'progress',
    timestamp: '2025-06-19 17:45',
    details: {
      '所属项目': '产品事业部CRM系统',
      '任务名称': '产品阶段',
      '完成进度': '50%',
    },
  },
  {
    id: 4,
    title: '任务延期',
    status: '未读',
    type: 'delay',
    timestamp: '2025-06-20 10:00',
    details: {
      '所属项目': '产品事业部CRM系统',
      '任务名称': 'UI设计',
      '延期天数': '2天',
    },
  },
];

const messageTypes = [
  { value: 'all', label: '全部类型' },
  { value: 'payment', label: '项目回款提醒' },
  { value: 'task', label: '任务指派提醒' },
  { value: 'progress', label: '项目进度提醒' },
  { value: 'delay', label: '任务延期' },
];

export default function ProjectMessages() {
  const [allMessages, setAllMessages] = useState(mockMessages);
  const [filteredMessages, setFilteredMessages] = useState(mockMessages);
  const [selectedMessage, setSelectedMessage] = useState(mockMessages[0]);
  const [activeSubTab, setActiveSubTab] = useState('all');
  const [selectedType, setSelectedType] = useState('all');
  const [dateRange, setDateRange] = useState(null);

  const applyFilters = (filters) => {
    const {
      source = allMessages,
      subTab = activeSubTab,
      type = selectedType,
      dates = dateRange,
    } = filters;

    let newFilteredData = [...source];

    // 1. 根据页签（状态）筛选
    if (subTab !== 'all') {
      newFilteredData = newFilteredData.filter((m) => m.status === subTab);
    }

    // 2. 根据消息类型筛选
    if (type !== 'all') {
      newFilteredData = newFilteredData.filter((m) => m.type === type);
    }

    // 3. 根据日期范围筛选
    if (dates && dates[0] && dates[1]) {
      const [start, end] = dates;
      newFilteredData = newFilteredData.filter((m) => {
        const messageDate = new Date(m.timestamp);
        return messageDate >= start.startOf('day').toDate() && messageDate <= end.endOf('day').toDate();
      });
    }

    setFilteredMessages(newFilteredData);

    // 如果当前选中的消息不在筛选结果中，则默认选中第一条，否则保持不变
    const isSelectedMessageInResult = newFilteredData.some(item => item.id === selectedMessage?.id);
    if (!isSelectedMessageInResult) {
      setSelectedMessage(newFilteredData.length > 0 ? newFilteredData[0] : null);
    }
  };

  const handleSubTabChange = (key) => {
    setActiveSubTab(key);
    // 切换页签时，重置筛选条件并应用
    setSelectedType('all');
    setDateRange(null);
    applyFilters({ subTab: key, type: 'all', dates: null });
  };
  
  const handleSearch = () => {
    applyFilters({}); // 使用当前 state 中的筛选条件
  };

  const handleReset = () => {
    // 重置筛选条件，并重新应用当前页签的筛选
    setSelectedType('all');
    setDateRange(null);
    applyFilters({ type: 'all', dates: null });
  };

  const handleMarkAllAsRead = () => {
    const updatedMessages = allMessages.map((m) => ({ ...m, status: '已读' }));
    setAllMessages(updatedMessages);
    // 更新数据源后，重新应用当前所有筛选条件
    applyFilters({ source: updatedMessages });
  };

  const renderMessageDetail = () => {
    if (!selectedMessage) {
      return (
        <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', height: '100%', background: '#fff', borderRadius: '4px' }}>
          <h2 style={{ color: '#666' }}>展示对应类别详情信息</h2>
          <p style={{ color: '#999' }}>如：客户审批，则展示客户详情</p>
        </div>
      );
    }

    return (
      <Card title={selectedMessage.title} style={{ height: '100%' }}>
        {Object.entries(selectedMessage.details).map(([key, value]) => (
          <Row key={key} style={{ marginBottom: 12 }}>
            <Col span={6} style={{ color: '#999', textAlign: 'right' }}>{key}：</Col>
            <Col span={18}>{value}</Col>
          </Row>
        ))}
        <div style={{ position: 'absolute', bottom: 20, right: 24, color: '#999' }}>
          {selectedMessage.timestamp}
        </div>
      </Card>
    );
  };

  const unreadCount = allMessages.filter(m => m.status === '未读').length;

  return (
    <div style={{ padding: '20px', background: '#f5f5f5' }}>
      <div style={{ background: '#fff', padding: '0 20px' }}>
        <Tabs defaultActiveKey="1" tabBarExtraContent={
          <div style={{ marginRight: 24, color: '#f8ac59', fontWeight: 'bold' }}>
            项目消息 <span style={{ background: '#f8ac59', color: '#fff', borderRadius: '8px', padding: '2px 6px' }}>{unreadCount}</span>
          </div>
        }>
          <TabPane tab="项目消息" key="1" />
        </Tabs>
      </div>

      <div style={{ marginTop: '20px', background: '#fff', padding: '20px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: '1px solid #eee', marginBottom: 20 }}>
          <Tabs activeKey={activeSubTab} onChange={handleSubTabChange} type="card" style={{ border: 0 }}>
            <TabPane tab="未读" key="未读" />
            <TabPane tab="已读" key="已读" />
            <TabPane tab="全部消息" key="all" />
          </Tabs>
          <Button type="link" onClick={handleMarkAllAsRead}>一键消息已读</Button>
        </div>

        <Space style={{ marginBottom: 20 }}>
          <span>选择类型:</span>
          <Select value={selectedType} style={{ width: 200 }} options={messageTypes} onChange={setSelectedType} />
          <span>时间:</span>
          <RangePicker value={dateRange} onChange={setDateRange} />
          <Button type="primary" onClick={handleSearch}>查询</Button>
          <Button onClick={handleReset}>重置</Button>
        </Space>

        <Row gutter={20}>
          <Col span={8}>
            <div style={{ height: 'calc(100vh - 400px)', overflowY: 'auto', paddingRight: '10px' }}>
              <List
                dataSource={filteredMessages}
                renderItem={(item) => (
                  <List.Item style={{ padding: 0, marginBottom: 10 }}>
                    <Card
                      hoverable
                      onClick={() => setSelectedMessage(item)}
                      style={{ width: '100%', border: selectedMessage?.id === item.id ? '1px solid #1890ff' : '1px solid #e8e8e8' }}
                      bodyStyle={{ padding: '16px' }}
                    >
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <span style={{ fontWeight: '500' }}>{item.title}</span>
                        <span style={{ color: item.status === '未读' ? 'red' : 'green' }}>{item.status}</span>
                      </div>
                      <div style={{ marginTop: 8 }}>
                        {Object.entries(item.details).slice(0, 2).map(([key, value]) => (
                           <div key={key} style={{ fontSize: 12, color: '#999', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{key}: {value}</div>
                        ))}
                      </div>
                      <div style={{ fontSize: 12, color: '#ccc', textAlign: 'right', marginTop: 8 }}>{item.timestamp}</div>
                    </Card>
                  </List.Item>
                )}
              />
            </div>
          </Col>
          <Col span={16}>
            <div style={{ height: 'calc(100vh - 400px)' }}>
              {renderMessageDetail()}
            </div>
          </Col>
        </Row>
      </div>
    </div>
  );
}
